<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "product_material".
 *
 * @property integer $id
 * @property integer $product_id
 * @property integer $type
 * @property integer $entry_id
 * @property double $num
 * @property string $create_at
 * @property string $update_at
 *
 * @property Material|Product $entry
 * @property Product $product
 */
class ProductMaterial extends \app\models\BaseModel {
    const TYPE_OTHER = 0;
    const TYPE_MATERIAL = 1;
    const TYPE_PRODUCT = 2;
    public static $roles = [
        self::TYPE_MATERIAL => '原料',
        self::TYPE_PRODUCT => '产品',
    ];

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'product_material';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['product_id', 'type', 'entry_id'], 'required'],
            [['product_id', 'type', 'entry_id'], 'integer'],
            [['num'], 'number'],
            [['create_at', 'update_at'], 'safe'],
            [['product_id'], 'exist', 'skipOnError' => true, 'targetClass' => Product::className(), 'targetAttribute' => ['product_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'product_id' => 'Product ID',
            'type' => '原料类型',
            'entry_id' => 'Entry ID',
            'num' => 'Num',
            'create_at' => '创建时间',
            'update_at' => '更新时间',
        ];
    }

    public function fields() {
        $fields = [
            'id',
            'entry',
            'type',
            'num',
        ];
        $fields = array_combine($fields, $fields);

        return $fields;
    }

    public function extraFields() {
        $fields = [
            'product_id',
            'entry_id',
            'create_at',
            'update_at',
        ];
        $fields = array_combine($fields, $fields);
        return $fields;
    }

    public function getEntry() {
        if($this->type == self::TYPE_MATERIAL) {
            return $this->hasOne(Material::className(), ['id' => 'entry_id']);
        } else {
            return $this->hasOne(Product::className(), ['id' => 'entry_id']);
        }
    }

    public function getProduct() {
        return $this->hasOne(Product::className(), ['id' => 'product_id'])->inverseOf('productMaterials');
    }
}
